////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2013 Charles Teague                                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using RPSDAL;
using RPSDAL.CollectionClasses;
using RPSDAL.EntityClasses;
using RPSDAL.HelperClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;


public partial class ContactGroupList : System.Web.UI.Page
{

    protected override void OnInit(System.EventArgs e)
    {
        if (Parameters.LoggedUser != -1)
        {
            UserEntity eUser = new UserEntity(Parameters.LoggedUser);
            RoleEntity eRole = new RoleEntity(eUser.RoleId);

            if (!eRole.HasViewContactGroup)
            {
                Parameters.LoggedUser = -1;
                Response.Redirect("Default.aspx");
                return;
            }
        }

        grdContactGroups.PageSize = Parameters.PageSize;
        LoadContactGroups();
    }

    /// <summary>
    /// load all contacts into the contact list
    /// </summary>
    private void LoadContactGroups()
    {
        ContactGroupCollection cContactGroups = new ContactGroupCollection();
        cContactGroups.GetMulti(null);

        grdContactGroups.DataSource = cContactGroups;
        grdContactGroups.DataBind();

        if (Parameters.LoggedUser != -1)
        {
            UserEntity eUser = new UserEntity(Parameters.LoggedUser);
            RoleEntity eRole = new RoleEntity(eUser.RoleId);

            if (!eRole.HasEditContactGroup) 
            {
                grdContactGroups.Columns[2].Visible = false;
                grdContactGroups.Columns[3].Visible = false;
                btnAddNewContactGroup.Visible = false;
            }
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {

    }

    #region user interface


    /// <summary>
    /// treat edit/ remove commands
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Command(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Page")
        {
            return;
        }
        if (((System.Web.UI.WebControls.Button)(e.CommandSource)).Text == "Edit")
        {
            Global.UserLogSave(Parameters.LoggedUser, "Edit Contact Group id=" + e.CommandArgument.ToString());
            Response.Redirect("ContactGroup.aspx?id=" + Global.EncryptString(e.CommandArgument.ToString()));
        }
        else
        {
            // remove contact group

            Global.UserLogSave(Parameters.LoggedUser, "Remove Contact Group id=" + e.CommandArgument.ToString());

            int contactGroupId = Convert.ToInt32(e.CommandArgument);
            ContactGroupEntity eContactGroup = new ContactGroupEntity(contactGroupId);

            // delete business rules for this contact group
            BusinessRuleCollection cBusinessRules = new BusinessRuleCollection();
            IPredicateExpression filter = new PredicateExpression();
            filter.Add(BusinessRuleFields.ContactGroupId == eContactGroup.ContactGroupId);
            cBusinessRules.GetMulti(filter);

            for (int i = 0; i < cBusinessRules.Count; i++)
            {
                LetterCollection cLetters = new LetterCollection();
                IPredicateExpression filterLetter = new PredicateExpression();
                filterLetter.Add(LetterFields.BusinessRulesId == cBusinessRules[i].BusinessRuleId);
                cLetters.DeleteMulti(filterLetter);

                CallCollection cCalls = new CallCollection();
                IPredicateExpression filterCall = new PredicateExpression();
                filterCall.Add(CallFields.BusinessRuleId == cBusinessRules[i].BusinessRuleId);
                cCalls.GetMulti(filterCall);

                for (int j = 0; j < cCalls.Count; j++)
                {
                    CallFinishedValueCollection cCallFinishedValues = new CallFinishedValueCollection();
                    IPredicateExpression filterCallFinishedValue = new PredicateExpression();
                    filterCallFinishedValue.Add(CallFinishedValueFields.CallId == cCalls[j].CallId);
                    cCallFinishedValues.DeleteMulti(filterCallFinishedValue);
                }

                cCalls.DeleteMulti(filterCall);
            }

            cBusinessRules.DeleteMulti(filter);

            // delete group members
            ContactGroupMemberCollection cContactGroupMembers = new ContactGroupMemberCollection();
            IPredicateExpression filterContactGroupMember = new PredicateExpression();
            filterContactGroupMember.Add(ContactGroupMemberFields.ContactGroupId == eContactGroup.ContactGroupId);
            cContactGroupMembers.DeleteMulti(filterContactGroupMember);

            eContactGroup.Delete();

            Response.Redirect("ContactGroupList.aspx");
        }
    }

    /// <summary>
    /// attach javascript actions to grid view buttons
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button button = (Button)e.Row.FindControl("btnRemove");
            button.Attributes.Add("onclick", @"javascript:return confirm('Are you sure you want to delete this contact group? This will delete everything related to it (business rules, letters etc.). ');");
        }
    }

    /// <summary>
    /// add new contact group
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void AddNewContactGroup(object sender, EventArgs e)
    {
        Global.UserLogSave(Parameters.LoggedUser, "Add New Contact Group");
        Response.Redirect("ContactGroup.aspx");
    }

    protected void grdContactGroups_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdContactGroups.PageIndex = e.NewPageIndex;
        LoadContactGroups();
    }

    #endregion user interface

   
}
